package com.imy.lua.lib.screen;

import android.content.Context;
import android.os.ConditionVariable;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.immomo.mls.LuaViewManager;
import com.immomo.mls.annotation.LuaClass;
import com.immomo.mls.annotation.LuaBridge;
import com.immomo.mls.utils.LVCallback;
import com.immomo.mls.wrapper.callback.IVoidCallback;
import com.imy.common.util.ALog;
import com.imy.common.util.FileUtils;
import com.imy.lua.helper.screen.ScreenHelper;

import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;

/**
 * Created by MLN Template
 * 注册方法：
 * new MLSBuilder.SIHolder(UDScreen.LUA_CLASS_NAME, UDScreen.class)
 */
@LuaClass
public class UDScreen {
    /**
     * Lua类型，Lua调用方法（和静态调用相同）：
     * Screen:method()
     */
    public static final String LUA_CLASS_NAME = "Screen";

    /**
     * 直接在属性中增加注解，可让Lua有相关属性
     * eg:
     * Screen:property()      --获取相关值
     * Screen:property(10)    --设置相关值
     */


    @LuaBridge
    public String capture(LuaValue[] luaValues) {
        ALog.i("capture");
        String path = null;
        if (luaValues.length > 1) {
            path = luaValues[1].toJavaString();
        } else {
            String rootScreenFilePath = FileUtils.createRootScreenFilePath();
            path = rootScreenFilePath + "/screen.png";
        }
        final String[] callBack = {""};
        if (TextUtils.isEmpty(path)) {
            callBack[0] = "path is null";
            return callBack[0];
        }
        ConditionVariable lock = new ConditionVariable();
        ScreenHelper.get().startScreen(path, new ScreenHelper.OnScreenCaptureListener() {
            @Override
            public void onSuccess(String path) {
                callBack[0] = path;
                lock.open();
            }

            @Override
            public void onFail() {
                callBack[0] = "capture fail";
                lock.open();
            }
        });
        lock.block();
        return callBack[0];
    }
    //<editor-fold desc="Other Constructor">
    /**
     * Lua构造函数，不关心初始化参数
     * @param g 虚拟机
     */
    //public UDScreen(@NonNull Globals g) {}

    /**
     * Lua构造函数，不需要虚拟机及上下文环境
     * @param init 初始化参数
     */
    //public UDScreen(@NonNull LuaValue[] init) {}

    /**
     * Lua构造函数，不需要虚拟机，不关心初始化参数
     */
    //public UDScreen() {}
    //</editor-fold>

    /**
     * Lua构造函数
     *
     * @param g    虚拟机
     * @param init 构造方法中传入的参数
     */
    public UDScreen(@NonNull Globals g, @NonNull LuaValue[] init) {

    }

    //<editor-fold desc="Bridge API">

    /**
     * 获取上下文，一般情况，此上下文为Activity
     *
     * @param globals 虚拟机，可通过构造函数存储
     */
    protected Context getContext(@NonNull Globals globals) {
        LuaViewManager m = (LuaViewManager) globals.getJavaUserdata();
        return m != null ? m.context : null;
    }

}
